import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class NameSeal {
    public static void main(String[] args) {
        // 输入名字和字体大小
        String name = "王看看";
        int fontSize = 30;

        // 创建字体
        Font font = new Font("宋体", Font.BOLD, fontSize);

        // 测量文字的宽度和高度
        BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = tempImage.createGraphics();
        g2d.setFont(font);
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(name);
        int textHeight = fontMetrics.getHeight();
        g2d.dispose();

        // 创建最终图像
        BufferedImage image = new BufferedImage(textWidth + 20, textHeight + 20, BufferedImage.TYPE_INT_ARGB);
        g2d = image.createGraphics();

        // 设置透明背景
        g2d.setComposite(AlphaComposite.Clear);
        g2d.fillRect(0, 0, image.getWidth(), image.getHeight());

        // 画红色方框和文字
        g2d.setComposite(AlphaComposite.Src);
        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(5));
        g2d.drawRect(5, 5, textWidth + 10, textHeight + 10);

        g2d.setFont(font);
        g2d.drawString(name, 10, textHeight - fontMetrics.getDescent() + 10);

        g2d.dispose();

        // 保存图片
        try {
            ImageIO.write(image, "PNG", new File("C:\\Users\\tlcb\\Pictures\\Camera Roll\\mingimage0618.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
